import axios from 'axios';

const apiClient = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json',
  },
});

apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const login = async (data: any) => {
  const response = await apiClient.post('/login', data);
  return response.data;
};

export const signup = async (data: any) => {
  const response = await apiClient.post('/signup', data);
  return response.data;
};

export const getPosts = async () => {
  const response = await apiClient.get('/posts/');
  return response.data;
};

export const getPost = async (id: string) => {
  const response = await apiClient.get(`/posts/${id}`);
  return response.data;
};


export const createPost = async (data: { title: string; content: string }) => {
  const response = await apiClient.post('/posts/', data);
  return response.data;
};

export const votePost = async (postId: string, voteType: number) => {
  const response = await apiClient.post(`/posts/${postId}/vote`, { vote_type: voteType });
  return response.data;
};

export const getUserVotes = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    return [];
  }
  try {
    const response = await apiClient.get('/votes/');
    return response.data || [];
  } catch (error) {
    console.error('Failed to get user votes', error);
    return [];
  }
};

export const getHotPosts = async () => {
  const response = await apiClient.get('/posts/hot');
  return response.data;
};